#
#  Copyright (C) 2009 GSyC/LibreSoft
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 
#    Author : Jose Antonio Santos Cadenas <jcaden __at__ gsyc __dot__ es>
#


# Create your views here.
import sys

from format.utils import  getResponseFormat, generateResponse
from social.core import api
from social.core.config import ALLOWED_SEARCH
from social.rest.forms import LoginForm, PhotoForm, SoundForm

from django.http import HttpResponse

from utils import error, get_slice, get_limits, get_num_pages

import string

def forbbiden_photo(request):
    format = getResponseFormat (request)    
    return error(format, "You don't have permission to access here", code='405')

def user_login (request):
    format = getResponseFormat (request)

    if request.method == "POST":
        loginform = LoginForm(request.POST)
        id=loginform.login(request)
        if id:
            data = {'code'         : '200',
                    'id'           : id,
                    'description'  : 'User logged in',}
            return generateResponse(format, data, "ok")
        else:
            return error(format, "User and password do not match") 
    else:
        return error(format, "Need a post petition")

def user_create_or_modify (request, modify=False):
    REGISTER_MANDATORY_FIELDS = []
    REGISTER_OPTIONAL_FIELDS = ["latitude", "longitude", "altitude", "radius", 
                                "birthday", "country", "post_code", "first_name", "first_name", "email"]
                
    format = getResponseFormat (request)
    if modify:
        if not request.user.is_authenticated():
            return error(format, "The user is not authenticated")
    if request.method == "POST":
        if ("password" in request.POST) and ("username" in request.POST):
            try:
                passwd=request.POST['password']
                user=request.POST['username']
                p={'username':user,'password':passwd}
  
                for field in REGISTER_MANDATORY_FIELDS:
                    print field
                    if field in request.POST:
                        p[field] = request.POST[field]
                    else:
                        return error(format ,'Missing parameters')
                
                for field in REGISTER_OPTIONAL_FIELDS:
                    if field in request.POST:
                        p[field] = request.POST[field]
                        
                if ("new_password" in request.POST):  
                    p["new_password"]=request.POST["new_password"]

                if modify:
                    if user == request.user.username:
                        correct, message=api.user.create_or_modify(p, modify=True)
                        if correct:
                            data = {'code'         : '200',
                                    'description'  : 'User modified correctly',}
                            return generateResponse(format, data, "ok")
                        else:
                            return error(format, message)
                    else:
                        return error(format, "You can not modify your username")
                else:
                    correct, message=api.user.create_or_modify(p, modify=False)
                    if correct:
                        data = {'code'         : '200',
                                'id'           : message,
                                'description'  : 'User created correctly',}
                        return generateResponse(format, data, "ok")
                    else:
                        return error(format, message)
            except ValueError:
                print ValueError
                return error(format ,'Unknown error occurred')               
        else:
            return error (format, 'Missing parameters')
    else:
        return error (format, 'Need a POST petition')
    
def user_set_avatar(request, user=None):
    format = getResponseFormat (request)
    if request.method != "POST":
        return error (format, "Need a POST petition")
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    try:
        photo_id = request.POST["photo_id"]
    except:
        return error(format, "Needs a POST parameter 'photo_id' with the id of the photo")
    correct, message = api.user.set_avatar(request.user.id, photo_id)
    if correct:
        data = {'code'         : '200',
                'description'  : 'Avatar changed'}
        return generateResponse(format, data, "ok")
    else:
        return error(format, message)
    
def user_set_status(request):
    format = getResponseFormat (request)
    if request.method != "POST":
        return error (format, "Need a POST petition")
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    try:
        status = request.POST["status"]
    except:
        return error(format, "Needs a POST parameter 'status' with the new status")
    correct, message = api.user.set_status(request.user.id, status)
    if correct:
        data = {'code'         : '200',
                'description'  : 'Status updated'}
        return generateResponse(format, data, "ok")
    else:
        return error(format, message)
    
def user_position (request, user=None):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        if user==None:
            u_id=request.user.id
        else:
            u_id=user
        if u_id!=request.user.id:
            return error(format, "You can only modify your position")
        if ("latitude" in request.POST) and ("longitude" in request.POST):
            latitude=request.POST["latitude"]
            longitude=request.POST["longitude"]
            if ("radius" in request.POST):
                radius=request.POST["radius"]
            else:
                radius=None
            if ("altitude" in request.POST):
                altitude=request.POST["altitude"]
            else:
                altitude=None
            if radius != None and altitude != None:
                correct, message = api.node.set_coordinates(u_id, latitude, longitude, altitude=altitude, radius=radius)
            elif radius != None:
                correct, message = api.node.set_coordinates(u_id, latitude, longitude, radius=radius)
            elif altitude != None:
                correct, message = api.node.set_coordinates(u_id, latitude, longitude, altitude=altitude)
            else:
                correct, message = api.node.set_coordinates(u_id, latitude, longitude)
            if correct:
                data = { 'code'         : '200',
                         'description'  : 'Position updated'}
                return generateResponse(format, data, "ok")
            else:
                return error(format, message)
        else:
            return error (format, 'Missing parameters')
    else:
        return error (format, 'Need a POST petition')

def user_data (request, user):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    p=api.user.get_data(user, request.user)
    if p==None:
        return error (format, 'User doesn\'t exist')
    data = {"code"    : "200",
            "user"    : p,
            "request" : request}
    return generateResponse(format, data, "user/data")

def user_my_data (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    return user_data(request, request.user.id)
        
def user_delete (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        if ("userid" in request.POST):
            user=request.POST['userid']
            if eval(user) != request.user.id:
                return error(format, "You can only delete your user")
            correct, message=api.user.delete(user)
            if correct:
                data = {'code'         : '200',
                        'description'  : 'User deleted correctly',}
                return generateResponse(format, data, "ok")
            else:
                return error (format, message)               
        else:
            return error (format, 'Missing parameters')
    else:
        return error (format, 'Need a POST petition')

def user_all(request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    f, t, page, elems = get_limits(request)
    users, n_total_users = api.user.get_all(f, t, request.user)
    
    total_pages = get_num_pages(n_total_users, elems)
    
    #users, page, elems = get_slice(request, users)
    data = {"code"  : '200',
            "users" : users,
            "page"  : page,
            "elems" : len(users),
            'total_pages' : total_pages,
            "type"  : "user_list" }
    
    return generateResponse(format, data, "user/list")

def user_friends(request, user=None):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if user==None:
        user=request.user.id
    f, t, page, elems = get_limits(request)
    users, n_total_users =api.user.get_friends(user, f, t, viewer=request.user)
    
    total_pages = get_num_pages(n_total_users, elems)
    
    #users, page, elems = get_slice(request, users)
    data = {"code"  : '200',
            "users" : users,
            "page"  : page,
            "elems": len(users),
            'total_pages' : total_pages,
            "type"  : "user_list" }

    return generateResponse(format, data, "user/list")

def user_friendship_invitations(request, user=None):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if user==None:
        user=request.user.id
    f, t, page, elems = get_limits(request)
    users, n_total_users = api.user.get_friendship_invitations(user, f, t, viewer=request.user)
    
    total_pages = get_num_pages(n_total_users, elems)
    
    #users, page, elems = get_slice(request, users)
    data = {"code"  : '200',
            "users" : users,
            "page"  : page,
            "elems" : len(users),
            'total_pages' : total_pages,
            "type"  : "user_list" }
    return generateResponse(format, data, "user/list")

def user_near_friends(request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    try:
        radius=request.REQUEST["r"]
    except:
        return error(format, 'Need a (get or post) "r" parameter with the radius')
    f, t, page, elems = get_limits(request)
    users=api.user.get_nearby_friends(request.user.id, radius, f, t, request.user)
    #users, page, elems = get_slice(request, users)
    data = {"code"  : '200',
            "users" : users,
            "page"  : page,
            "elems" : len(users),
            "type"  : "user_list" }
    return generateResponse(format, data, "user/list")

def user_near(request, user=None):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    try:
        radius=request.REQUEST["r"]
    except:
        return error(format, 'Need a (get or post) "r" parameter with the radius')
    if user==None:
        user=request.user.id
    f, t, page, elems = get_limits(request)
    users=api.user.get_nearby_people(user, radius, f, t, request.user)
    #users, page, elems = get_slice(request, users)
    data = {"code"  : '200',
            "users" : users,
            "page"  : page,
            "elems" : len(users),
            "type"  : "user_list" }
    return generateResponse(format, data, "user/list")

def user_photos (request, user=None):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    try:
        if user==None:
            user=request.user.id
        f, t, page, elems = get_limits(request)
        photos = api.photo.get_for_user(user, f, t, request.user)
        #photos, page, elems = get_slice(request, photos) 
        data = {'code'     : '200',  
                'photos'   : photos,
                "page"     : page,
                "elems"    : len(photos),
                "type"     : "photos_list" }
        return generateResponse(format, data, "photo/list")
    except:
        return error(format, 'Some errors occurred')    
    
def user_sounds (request, user=None):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    try:
        if user==None:
            user=request.user.id
        f, t, page, elems = get_limits(request)
        sounds = api.sound.get_for_user(user, f, t, request.user)
        #sounds, page, elems = get_slice(request, sounds) 
        data = {'code'     : '200',  
                'sounds'   : sounds,
                "page"     : page,
                "elems"    : len(sounds),
                "type"     : "sounds_list" }
        return generateResponse(format, data, "sound/list")
    except:
        return error(format, 'Some errors occurred')

def user_notes (request, user=None):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    try:
        if user==None:
            user=request.user.id
        f, t, page, elems = get_limits(request)
        notes = api.note.get_for_user(user, f, t, request.user)
        #notes, page, elems = get_slice(request, notes)
        data = {'code'    : '200',
                'notes'   : notes,
                "page"    : page,
                "elems"   : len(notes),
                "type"    : "note_list" }
        return generateResponse(format, data, "note/list")
    except:
        return error(format, 'Some errors occurred')

def user_relation (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method=='POST':
        if ("userid1" in request.POST) and ("userid2" in request.POST):
            user1=request.POST['userid1']
            user2=request.POST['userid2']
            correct, message=api.user.create_friendship(user1, user2)
            if correct:
                data = {'code'         : '200',
                       'description'   : 'Relation created correctly',}
                return generateResponse(format, data, "ok")
            else:
                return error (format, message)
        else:
            return error (format, 'Missing parameters')
    else:
        return error (format, 'Need a POST petition')

def user_relation_delete (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method=='POST':
        if ("userid1" in request.POST) and ("userid2" in request.POST):
            user1=request.POST['userid1']
            user2=request.POST['userid2']
            correct, message=api.user.delete_friendship(user1, user2)
            if correct:
                data = {'code'        : '200',
                       'description'  : 'Relation deleted correctly',}
                return generateResponse(format, data, "ok")
            else:
                return error (format,  message)
        else:
            return error (format, 'Missing parameters')
    else:
        return error (format, 'Need a POST petition')
    
def user_groups (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    try:
        groups=api.group.get_for_user(request.user)
        data = {'code'      : '200',
                'groups'   : groups}
        return generateResponse(format, data, "group/list")
    except:
        return error(format, 'Some errors occurred')
    
def node_tag(request, node_id):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        if "tags" in request.POST:
            tags=request.POST["tags"]
            correct, message = api.node.set_tag(node_id, tags)
            if correct:
                data = { 'code'         : '200',
                         'description'  : 'Tags set correctly'}
                return generateResponse(format, data, "ok")
            else:
                return error(format, message) 
        else:
            return error (format, 'Missing parameters')
    else:
        return error (format, 'Need a POST petition')
    
def node_untag(request, node_id):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        if "tags" in request.POST:
            tags=request.POST["tags"]
            correct, message = api.node.remove_tag(node_id, tags)
            if correct:
                data = { 'code'         : '200',
                         'description'  : 'Tags removed correctly'}
                return generateResponse(format, data, "ok")
            else:
                return error(format, message) 
        else:
            return error (format, 'Missing parameters')
    else:
        return error (format, 'Need a POST petition')    

def node_comment(request, node_id):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        if "comment" in request.POST:
            comment=request.POST["comment"]
            correct, message = api.node.set_comment(node_id, comment, request.user.id)
            if correct:
                data = { 'code'         : '200',
                         'description'  : 'Comment added correctly'}
                return generateResponse(format, data, "ok")
            else:
                return error(format, message) 
        else:
            return error (format, 'Missing parameters')
    else:
        return error (format, 'Need a POST petition')
    
def node_delete_comment(request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        if "comment_id" in request.POST:
            comment_id = request.POST["comment_id"]
            correct, message = api.node.delete_comment(comment_id, request.user.id)
            if correct:
                data = { 'code'         : '200',
                         'description'  : 'Comment deleted correctly'}
                return generateResponse(format, data, "ok")
            else:
                return error(format, message) 
        else:
            return error (format, 'Missing parameters')
    else:
        return error (format, 'Need a POST petition')

def node_near(request, node):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    try:
        radius=request.REQUEST["r"]
    except:
        return error(format, 'Need a (get or post) "r" parameter with the radius')
    nodes=api.node.get_nearby_node(node, radius, request.user)
    data = {"code"  : '200',
            "nodes" : nodes }
    return generateResponse(format, data, "nodes/dist")

def node_list(request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    nodes=api.node.get_all(request.user)
    data = {"code"  : '200',
            "nodes" : nodes }
    return generateResponse(format, data, "nodes/list")

def node_data(request, node_id):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    try:
        node=api.node.get_data(node_id, request.user)
        if node == None:
            return error(format, 'Node doesn\'t exist')
        else:
            data = {"code" : "200",
                    "node" : node}
            return generateResponse(format, data, "nodes/data")
    except:
        return error(format, 'Some errors occurred')

def node_set_position (request, node_id):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        if ("latitude" in request.POST) and ("longitude" in request.POST):
            latitude=request.POST["latitude"]
            longitude=request.POST["longitude"]
            if ("radius" in request.POST):
                radius=request.POST["radius"]
            else:
                radius=None
            if ("altitude" in request.POST):
                altitude=request.POST["altitude"]
            else:
                altitude=None
            if radius != None and altitude != None:
                correct, message = api.node.set_coordinates(node_id, latitude, longitude, altitude=altitude, radius=radius)
            elif radius != None:
                correct, message = api.node.set_coordinates(node_id, latitude, longitude, radius=radius)
            elif altitude != None:
                correct, message = api.node.set_coordinates(node_id, latitude, longitude, altitude=altitude)
            else:
                correct, message = api.node.set_coordinates(node_id, latitude, longitude)
            if correct:
                data = { 'code'         : '200',
                         'description'  : 'Position updated'}
                return generateResponse(format, data, "ok")
            else:
                return error(format, message)
        else:
            return error (format, 'Missing parameters')
    else:
        return error (format, 'Need a POST petition')

def group_create (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        if ("groupname" in request.POST):
            group={'groupname':request.POST["groupname"]}
            correct, message=api.group.create_or_modify(group, modify=False)
            if correct:
                data = {'code'         : '200',
                        'id'           : message,
                        'description'  : 'Group created correctly',}
                return generateResponse(format, data, "ok")
            else:
                return error(format, message)               
        else:
            return error(format, 'Missing parameters')
    else:
        return error(format, 'Need a POST petition')

def group_list (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    try:
        groups=api.group.get_all(request.user.id)
        data = {'code'      : '200',
                'groups'   : groups}
        return generateResponse(format, data, "group/list")
    except:
        return error(format, 'Some errors occurred')

def group_data (request, group):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    try:
        group=api.group.get_data(group, request.user.id)
        if group == None:
            return error(format, 'Group doesn\'t exist')
        else:
            data = {"code" : "200",
                    "group" : group,
                    "request" : request}
            return generateResponse(format, data, "group/data")
    except:
        return error(format, 'Group doesn\'t exist')

def group_elements(request, group):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    try:
        elements=api.group.get_group_elements(group, request.user)
        data={"code": "200",
              "elements": elements}
        return generateResponse(format, data, "group/elements")
    except:
        return error(format, "Unknown error")

def group_delete (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        if ("groupid" in request.POST):
            group=request.POST['groupid']
            correct, message = api.group.delete(group)
            if correct:
                data = {'code'         : '200',
                        'description'  : 'Group deleted correctly',}
                return generateResponse(format, data, "ok")
            else:
                return error(format, message)               
        else:
            return error(format, 'Missing parameters')
    else:
        return error(format, 'Need a POST petition')

def group_join (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        if ("groupid" in request.POST) and ("userid" in request.POST):
            try:
                group=request.POST["groupid"]
                user=request.POST["userid"]
                correct, message = api.group.join(group, user)
                if correct:
                    data={'code'         : '200',
                          'description'  : 'Joined correctly',}
                    return generateResponse(format, data, "ok")
                else:
                    return error (format, message)
            except:
                return error(format, 'Unknown error occurred')               
        else:
            return error(format, 'Missing parameters')
    else:
        return error(format, 'Need a POST petition')

def group_join_delete (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        if ("groupid" in request.POST) and ("userid" in request.POST):
            try:
                group=request.POST["groupid"]
                user=request.POST["userid"]
                correct, message = api.group.unjoin (group, user)
                if correct:
                    data = {'code'         : '200',
                            'description'  : 'Unjoined correctly',}
                    return generateResponse(format, data, "ok")
                else:
                    return error(format, message)
            except:
                return error(format, 'Unknown error occurred')            
        else:
            return error(format, 'Missing parameters')
    else:
        return error(format, 'Need a POST petition')

def create_note (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        if request.user.is_authenticated():
            if ("text" in request.POST) and ("latitude" in request.POST) and \
             ("longitude" in request.POST) and ("title" in request.POST):
                note={"title"    : request.POST['title'],
                      "text"     : request.POST['text'],
                      "latitude" : request.POST['latitude'],
                      "longitude": request.POST['longitude'],
                      "owner"    : request.user.pk }
                if "altitude" in request.POST:
                    note["altitude"] = request.POST["altitude"]
                correct, message = api.note.create(note) 
                if correct:
                    data = {'code'         : '200',
                            'id'           : message,
                             'description'  : 'Note created correctly',}
                    return generateResponse(format, data, "ok")             
                else:
                    return error(format, message)
            else:
                return error(format, "Some POST parameters missing")
        else:
            return error(format, "The user must be logged in")
    else:
        return error(format, 'Need a POST petition')

def note_list (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    try:
        f, t, page, elems = get_limits(request)
        notes = api.note.get_all(f, t, viewer=request.user)
        #notes, page, elems = get_slice(request, notes)
        data = {'code'    : '200',
                'notes'   : notes,
                'page'    : page,
                'elems'   : len(notes),
                'type'    : "note_list" }
        return generateResponse(format, data, "note/list")
    except:
        return error(format, 'Some errors occurred')
    
def note_data(request, note_id):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    try:
        note=api.note.get_data(note_id, request.user)
        if note == None:
            return error(format, 'Note doesn\'t exist')
        else:
            data = {"code" : "200",
                    "note" : note,
                    "request" : request}
            return generateResponse(format, data, "note/data")
    except:
        return error(format, 'Some errors occurred')

def note_delete (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        if ("noteid" in request.POST):
            note_id=request.POST['noteid']
            correct, message = api.note.delete(note_id, request.user.id)
            if correct:
                data = {'code'         : '200',
                        'description'  : 'Note deleted correctly',}
                return generateResponse(format, data, "ok")
            else:
                return error(format, message)               
        else:
            return error(format, 'Missing parameters')
    else:
        return error(format, 'Need a POST petition')
    
##################################################################Here start question view##############################
#this function is used to set the question-answer server's location
def set_server(task):
    serverUrl = "http://localhost:8080/" 
    resourceUrl = "userpreferences/services/question/"
    url = serverUrl + resourceUrl
    if (task == "ask"):
        url = url + "discover/"
    if(task == "answer"):
        url = url + "answer/"    
    return url

#This function asks the server for a question
def question_get (request):
    url = set_server("ask")
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    try:
        question=api.question.get_data(url, request.user.id) 
        if question == "free":
            return error (format, "Something wrong happened with the connection to the question server")
        if question == "xml":
            return error (format, "Some errors ocurred parsing server's answer")
        if question == "error":
            return error(format, "There are not any questions available")
        if question == None:
            return error(format, "Something wrong happened")
        if question == "file":
            return error(format, "Some errors ocurred while saving the file")
        else:
            data = {'code'    : '200',
                    "question" : question,
                    "request" : request }
            return generateResponse(format, data, "question/data")
    except:
        return error(format, 'Some errors ocurred')

#This function sends to the server an answer
def send_answer (request):
    url = set_server("answer")
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        answer={}
        if "question_id" in request.POST:
            answer["id"] = request.POST['question_id']
        else:
            return error (format, "Need a POST param called 'question_id'") 
        if "answers" in request.POST:                       
            answer["answers"]=request.POST['answers']
        else:
            return error (format, "Need a POST param called 'answers'")
        if "comment" in request.POST:
            answer["comment"] = request.POST['comment']
        else:
            return error (format, "Need a POST param called 'comment'")
        answer["user"] = request.user.id
        answer["language"] = "es"
######################This is information for testing 
#    a = "1"
#    answer = {}
#    answer['id'] = 1
#    answer['email'] = "lcd@mimail.com"
#    answer['language'] = "es"
#    answer['answers'] = a
#    answer['comment'] = "hello world"
    try:
        response=api.question.send_data(url, answer)
        if response == "free":
            return error (format, "Something wrong happened with the connection to the question server")
        if response == "xml":
            return error (format, "Some errors ocurred parsing server's answer")
        if response == "error":
            return error (format, "Error at the Question Server")
        if response == "file":
            return error (format, "Some errors ocurred while saving the answers on the file")
        else:    
            message = "Successful operation"    
        data = {'code'    : '200',
                "state" : response,
                    "message" : message,
                    "request" : request }
        return generateResponse(format, data, "question/resp")
    except:
        return error(format, 'Something wrong happened')     
    

def photo_upload (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    try:
        if request.method == "POST":
            photo={}
            if "latitude" in request.POST:
                photo["latitude"] = request.POST['latitude']
            else:
                return error (format, "Need a POST param called 'latitude'")
            if "longitude" in request.POST:
                photo["longitude"] = request.POST['longitude']
            else:
                return error (format, "Need a POST param called 'longitude'")
            if "description" in request.POST:
                photo["description"] = request.POST['description']
            else:
                return error (format, "Need a POST param called 'description'")
            if "altitude" in request.POST:
                photo["altitude"] = request.POST["altitude"]
            form = PhotoForm(request.POST, request.FILES)
            if form.is_valid():
                try:
                    clean_data = form.cleaned_data
                    photo["photo_data"] = clean_data['photo']
                    photo["photo_name"] = clean_data['name']
                    photo["uploader"] = request.user.pk
                    correct, message = api.photo.upload (photo)
                    if correct:
                        data = {'code'         : '200',
                                'id'           : message,
                                'description'  : 'Photo uploaded correctly',}
                        return generateResponse(format, data, "ok")             
                    else:
                        return error(format, message)
                except:
                    return error (format, sys.exc_value)
            else:
                return error (format, "Sent data not valid")
        else:
            return error (format, "Need a POST petition")
    except:
        return error (format, sys.exc_value)

def photo_list (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    try:
        f, t, page, elems = get_limits(request)
        photos = api.photo.get_all(f, t, request.user)
        #photos, page, elems = get_slice(request, photos)
        data = {'code'    : '200',
                'photos'  : photos,
                'page'    : page,
                'elems'   : len(photos),
                'type'    : "photo_list" }
        return generateResponse(format, data, "photo/list")
    except:
        return error(format, 'Some errors occurred')    

def photo_data(request, photo_id):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    try:
        photo=api.photo.get_data(photo_id, request.user)
        if photo == None:
            return error(format, 'Photo doesn\'t exist')
        else:
            data = {"code"  : "200",
                    "photo" : photo,
                    "request" : request}
            return generateResponse(format, data, "photo/data")
    except:
        return error(format, "Some error occurred")
    
def photo_image(request, photo_id, thumb=False, size=None):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    try:
        if thumb:
            image_path = api.photo.get_image_path(photo_id, thumb=True, viewer=request.user)
        else:
            if size=="medium":
                image_path = api.photo.get_image_path(photo_id, (500, 500), viewer=request.user)
            elif size=="small":
                image_path = api.photo.get_image_path(photo_id, (250, 250), viewer=request.user)
            elif size=="large":
                image_path = api.photo.get_image_path(photo_id, (800, 800), viewer=request.user)
            else:
                image_path=api.photo.get_image_path(photo_id, viewer=request.user) 
        if image_path == None:
            return error(format, 'Photo doesn\'t exist or you don\'t have permission for view it')
        image_data = open(image_path, "rb").read()
        return HttpResponse(image_data, mimetype="image/jpeg")
    except:
        return error(format, "Some error occurred")

def photo_delete (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        if ("photoid" in request.POST):
            photo_id=request.POST['photoid']
            correct, message = api.photo.delete(photo_id, request.user.id)
            if correct:
                data = {'code'         : '200',
                        'description'  : 'Photo deleted correctly',}
                return generateResponse(format, data, "ok")
            else:
                return error(format, message)               
        else:
            return error(format, 'Missing parameters')
    else:
        return error(format, 'Need a POST petition')

def sound_upload (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    try:
        if request.method == "POST":
            sound={}
            if "latitude" in request.POST:
                sound["latitude"] = request.POST['latitude']
            else:
                return error (format, "Need a POST param called 'latitude'")
            if "longitude" in request.POST:
                sound["longitude"] = request.POST['longitude']
            else:
                return error (format, "Need a POST param called 'longitude'")
            if "description" in request.POST:
                sound["description"] = request.POST['description']
            else:
                return error (format, "Need a POST param called 'description'")
            if "altitude" in request.POST:
                sound["altitude"] = request.POST["altitude"]
            form = SoundForm(request.POST, request.FILES)
            if form.is_valid():
                try:
                    clean_data = form.cleaned_data
                    sound["sound_data"] = clean_data['sound']
                    sound["sound_name"] = clean_data['name']
                    sound["uploader"] = request.user.pk
                    correct, message = api.sound.upload (sound)
                    if correct:
                        data = {'code'         : '200',
                                'id'           : message,
                                'description'  : 'Sound uploaded correctly',}
                        return generateResponse(format, data, "ok")             
                    else:
                        return error(format, message)
                except:
                    return error (format, sys.exc_value)
            else:
                return error (format, "Sent data not valid")
        else:
            return error (format, "Need a POST petition")
    except:
        return error (format, sys.exc_info())

def sound_list (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    try:
        f, t, page, elems = get_limits(request)
        sounds = api.sound.get_all(f, t, request.user)
        #sounds, page, elems = get_slice(request, sounds)
        data = {'code'    : '200',
                'sounds'  : sounds,
                'page'    : page,
                'elems'   : len(sounds),
                'type'    : "photo_list" }
        return generateResponse(format, data, "sound/list")
    except:
        return error(format, 'Some errors occurred') 

def sound_data(request, sound_id):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    try:
        sound=api.sound.get_data(sound_id, request.user)
        if sound == None:
            return error(format, 'Sound doesn\'t exist')
        else:
            data = {"code"  : "200",
                    "sound" : sound,
                    "request" : request}
            return generateResponse(format, data, "sound/data")
    except:
        return error(format, "Some error occurred")

def sound_file(request, sound_id):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    try:
        file_path=api.sound.get_file_path(sound_id, viewer=request.user) 
        if file_path == None:
            return error(format, 'Sound doesn\'t exist or you don\'t have permission for view it')
        file_data = open(file_path, "rb").read()
        return HttpResponse(file_data, mimetype="audio/3gpp")
    except:
        return error(format, "Some error occurred")

def sound_delete (request):
    format = getResponseFormat (request)
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    if request.method == "POST":
        if ("soundid" in request.POST):
            sound_id=request.POST['soundid']
            correct, message = api.sound.delete(sound_id, request.user.id)
            if correct:
                data = {'code'         : '200',
                        'description'  : 'Sound deleted correctly',}
                return generateResponse(format, data, "ok")
            else:
                return error(format, message)               
        else:
            return error(format, 'Missing parameters')
    else:
        return error(format, 'Need a POST petition')

def version(request):
    format = getResponseFormat (request)
    ver=api.get_version()
    data={"code"   : "200",
          "version": ver}
    return generateResponse(format, data, "version")
    
def search(request):
    format = getResponseFormat(request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    
    if "dist" in request.REQUEST:
        dist=request.REQUEST["dist"]
    else:
        dist=-1
    if "terms" in request.REQUEST:
        terms=request.REQUEST["terms"]
    else:
        terms=""
    if "models" in request.REQUEST:
        models = string.split(request.REQUEST["models"])
    else:
        models = ALLOWED_SEARCH
    results=api.search (request.user, models, terms, dist)
    data ={"code"   : "200",
           "results": results}
    
    return generateResponse(format, data, "search/list")

def tag_list(request, tag):
    format = getResponseFormat(request)
    if not request.user.is_authenticated():
        return error (format, "The user is not authenticated")
    
    if "models" in request.REQUEST:
        models = string.split(request.REQUEST["models"])
    else:
        models = ALLOWED_SEARCH
    results=api.tags(models, tag, request.user.id)
    data ={"code"   : "200",
           "results": results}
    
    return generateResponse(format, data, "search/list")